package com.reservation.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.reservation.common.Result;
import com.reservation.entity.User;
import com.reservation.mapper.UserMapper;
import com.reservation.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户控制器
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private UserMapper userMapper;

    /**
     * 用户注册
     *
     * @param user 用户信息
     * @return 注册结果
     */
    @PostMapping("/register")
    public Result<User> register(@RequestBody @Valid User user) {
        User registeredUser = userService.register(user);
        return Result.success(registeredUser, "注册成功");
    }

    /**
     * 用户登录
     *
     * @param loginMap 登录参数
     * @return 登录结果
     */
    @PostMapping("/login")
    public Result<Map<String, Object>> login(@RequestBody Map<String, String> loginMap) {
        String username = loginMap.get("username");
        String password = loginMap.get("password");
        
        // 登录验证
        String token = userService.login(username, password);
        
        // 返回token和用户信息
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("token", token);
        User currentUser = userMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getUsername, username));
        resultMap.put("userInfo",userService.getUserInfo(currentUser.getId()));
        return Result.success(resultMap, "登录成功");
    }

    /**
     * 获取当前用户信息
     *
     * @return 用户信息
     */
    @GetMapping("/info")
    public Result<User> getUserInfo(@RequestParam Long id) {
        User user = userService.getUserInfo(id);
        return Result.success(user);
    }

    /**
     * 修改用户信息
     *
     * @param user 用户信息
     * @return 修改结果
     */
    @PutMapping("/info")
    public Result<User> updateUserInfo(@RequestBody @Valid User user) {
        User updatedUser = userService.updateUserInfo(user);
        return Result.success(updatedUser, "修改成功");
    }

    /**
     * 修改密码
     *
     * @param passwordMap 密码参数
     * @return 修改结果
     */
    @PutMapping("/password")
    public Result<Void> updatePassword(@RequestBody Map<String, String> passwordMap) {
        Long id = Long.valueOf(passwordMap.get("id"));
        String oldPassword = passwordMap.get("oldPassword");
        String newPassword = passwordMap.get("newPassword");
        
        boolean result = userService.updatePassword(id, oldPassword, newPassword);
        return Result.success(null, "密码修改成功");
    }

    /**
     * 分页查询用户列表（仅管理员可用）
     *
     * @param pageNum  当前页
     * @param pageSize     每页大小
     * @param username 用户名（可选）
     * @param name     姓名（可选）
     * @param role     角色（可选）
     * @return 用户列表
     */
    @GetMapping("/list")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<IPage<User>> getUserList(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String role) {
        Page<User> page = new Page<>(pageNum, pageSize);
        IPage<User> userPage = userService.getUserList(page, username, name, role);
        return Result.success(userPage);
    }

    /**
     * 删除用户（仅管理员可用）
     *
     * @param id 用户ID
     * @return 删除结果
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<Void> deleteUser(@PathVariable Long id) {
        boolean result = userService.deleteUser(id);
        return Result.success(null, "删除成功");
    }
}